# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import js2xml
from lxml import etree
import time
import logging

logger = logging.getLogger("peekLive")
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter(
    fmt="%(asctime)s %(name)s %(filename)s %(message)s",
    datefmt="%Y/%m/%d %X"
)

ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)


def room(yt_url,use_proxy:bool):
    proxies = {
        'http': '127.0.0.1:1080',
        'https': '127.0.0.1:1080'
    } if use_proxy else None

    print(proxies)

    session = requests.session()

    haveRoom = "false"
    waitMinute = 30

    while haveRoom == "false":
        r = session.get(yt_url, proxies=proxies)
        soup = BeautifulSoup(r.text, 'html.parser')
        myscripts = list(soup.select("script"))
        needScript = None
        for i, j in enumerate(myscripts):
            if len(j.contents) != 0 and j.contents[0].find("videoViewCountRenderer") != -1:
                needScript = i
                break
        if needScript is None:
            logger.info(f"Vtb is moyuing, wait {waitMinute} minute")
            time.sleep(waitMinute * 60)
            continue
        else:
            scriptStr = myscripts[needScript].string
            xmlOb = js2xml.parse(scriptStr)
            selector = etree.HTML(js2xml.pretty_print(xmlOb))
            haveRoom = selector.xpath('//property[@name="isLive"]/boolean')[0].text
            logger.info("Vtb create a livestreaming room.")

    session.close()

    if haveRoom == "false":
        return False
    else:
        return True


if __name__ == '__main__':
    # TODO: 外部传入
    # url = 'https://www.youtube.com/channel/UCeLzT-7b2PBcunJplmWtoDg/live'
    url = 'https://www.youtube.com/channel/UC0Owc36U9lOyi9Gx9Ic-4qg/live'
    room(url,True)
